package com.cloud.common.support;

import com.cloud.common.context.AppContext;
import org.springframework.data.redis.core.RedisTemplate;

public class Sequencer {

    private static final String KEY_PREFIX = "Sequence:";

    private static RedisTemplate<String, Object> getRedisTemplate() {
        return (RedisTemplate<String, Object>) AppContext.getBean(RedisTemplate.class);
    }

    /**
     * 初始化序列
     *
     * @param key
     * @param value
     */
    public static void init(String key, long value) {
        RedisTemplate<String, Object> redisTemplate = getRedisTemplate();
        redisTemplate.delete(KEY_PREFIX + key);
        redisTemplate.opsForValue().increment(KEY_PREFIX + key, value);
    }

    /**
     * 获取自增序列
     *
     * @return long
     */
    public static long increment(String key) {
        return getRedisTemplate().opsForValue().increment(KEY_PREFIX + key);
    }

}